//
//  MKUrlGuide.m
//  YangDongXi
//
//  Created by cocoa on 15/1/22.
//  Copyright (c) 2015年 yangdongxi. All rights reserved.
//

#import "MKUrlGuide.h"
#import "MKUrlGuideItem.h"
#import "MKUrlGuideParamItem.h"
#import "UIWindow+MKExtension.h"
#import "AppDelegate.h"
//#import "MKLoginViewController.h"
#import "MKWebViewController.h"
#import "SaveSelfCode.h"
#import "MKMultipleShopsHomePageController.h"
#import "MKNetworking+BusinessExtension.h"
#import "MBProgressHUD+MKExtension.h"
#import "QQYFirstMilkViewController.h"

@interface MKUrlGuide ()

@property (nonatomic, strong) NSMutableArray *guideItems;

@property (nonatomic, strong) NSMutableArray *delayGuideActions;

@property (nonatomic, assign) BOOL isNavigating;

@property (nonatomic, copy) NSString * thirdShopId;

@property (nonatomic, copy) NSString * couponId;

@end


@implementation MKUrlGuide

+ (MKUrlGuide *)commonGuide
{
    static MKUrlGuide *commonGuideInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^
    {
        commonGuideInstance = [[MKUrlGuide alloc] init];
        NSArray *data = [NSArray arrayWithContentsOfFile:
                             [[NSBundle mainBundle] pathForResource:@"MKUrlGuide" ofType:@"plist"]];
        
        for (NSDictionary *d in data)
        {
            MKUrlGuideItem *item = [[MKUrlGuideItem alloc] initWithDictionary:d];
            [commonGuideInstance.guideItems addObject:item];
        }
        //分享模块没有使用控制器，单独处理
        MKUrlGuideItem *item = [[MKUrlGuideItem alloc] init];
        item.command = share_command;
        [commonGuideInstance.guideItems addObject:item];
    });
    return commonGuideInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.guideItems = [NSMutableArray array];
        self.delayGuideActions = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNavigationControllerWillShow:) name:@"UINavigationControllerWillShowViewControllerNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNavigationControllerDidShow:) name:@"UINavigationControllerDidShowViewControllerNotification" object:nil];
    }
    return self;
}

//系统导航将要出现
- (void)handleNavigationControllerWillShow:(NSNotification *)noti
{
    self.isNavigating = YES;
}

//系统导航已经出现
- (void)handleNavigationControllerDidShow:(NSNotification *)noti
{
    self.isNavigating = NO;
    
    if (self.delayGuideActions.count > 0)
    {
        void(^block)() = [self.delayGuideActions firstObject];
        block();
        [self.delayGuideActions removeObjectAtIndex:0];
    }
}

//前缀判断，含以下前缀之一都可以处理，跳转到native页
- (NSString *)canHandle:(NSString *)string
{
    NSArray *ary = [NSArray arrayWithObjects:@"test.ybaby.com",@"www.ybaby.com/mobile",@"http://", nil];
    for (NSString *str in ary) {
        if ([string hasPrefix:str]) {
            return str;
        }
    }
    
    return  nil;

}

- (BOOL)guideForUrl:(NSString *)urlString
{
    return [self guideUrl:urlString ignoreNormal:NO];
}

- (BOOL)guideIgnoreWebVCForUrl:(NSString *)urlString
{
    return [self guideUrl:urlString ignoreNormal:YES];
}

- (BOOL)guideUrl:(NSString *)urlString ignoreNormal:(BOOL)ignore
{
    if ([urlString hasPrefix:@GUIDE_SCHEME])
    {
        NSString *newUrl = [urlString stringByReplacingOccurrencesOfString:@GUIDE_SCHEME withString:@"http://"];
        return [self guideUrl:newUrl ignoreNormal:NO];
    }
    [self saveSelfCode:urlString];
    NSRange range = [urlString rangeOfString:@"://"];
    if (range.location == NSNotFound)
    {
        return NO;
    }
    NSString *execStr = [urlString substringFromIndex:range.location + @"://".length];
    NSString *guidePrefix = [self canHandle:execStr];
    
    do
    {
        if (guidePrefix == nil) {
            break;
        }
        
        if (![execStr hasPrefix:guidePrefix])
        {
            break;
        }
        execStr = [execStr substringFromIndex:guidePrefix.length + 1];
        MKUrlGuideItem *matchedItem = nil;
        for (MKUrlGuideItem *item in self.guideItems)
        {
            
            if ([execStr hasPrefix:item.command])
            {
                matchedItem = item;
                break;
            }
        }
        if (matchedItem == nil)
        {
            NSString * detailStr = @"^item/([0-9]+).html$";
            NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", detailStr];
            BOOL res1 = [regextestmobile evaluateWithObject:execStr];
            if (res1) {
                for (MKUrlGuideItem *item in self.guideItems)
                {
                    
                    if ([item.command isEqualToString:@"detail.html"])
                    {
                        matchedItem = item;
                        NSDictionary * tempDic = @{@"urlParamName":@"item_uid",@"classParamName":@"itemId"};
                        MKUrlGuideParamItem * paramItem = [[MKUrlGuideParamItem alloc] initWithDictionary:tempDic];
                        matchedItem.params = @[paramItem];
                        break;
                    }
                }
            }else{
                NSString * detailStr = @"^getOffCoupon-([0-9]+).html$";
                NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", detailStr];
                BOOL res1 = [regextestmobile evaluateWithObject:execStr];
                if (res1) {
                    for (MKUrlGuideItem *item in self.guideItems)
                    {
                        
                        if ([item.command isEqualToString:@"my-coupon.html"])
                        {
                            matchedItem = item;
                            NSString * idSTring = [urlString stringByReplacingOccurrencesOfString:@"http://www.ybaby.com/mobile/" withString:@""];
                            idSTring = [idSTring stringByReplacingOccurrencesOfString:@".html" withString:@""];
                            int location = 0;
                            for (int i = 0; i < idSTring.length; i ++) {
                                if ([[idSTring substringWithRange:NSMakeRange(i, 1)] isEqualToString:@"-"]) {
                                    location = i + 1;
                                    break;
                                }
                            }
                            _couponId = [idSTring substringFromIndex:location];
                            break;
                        }
                    }
                }else{
                    break;
                }
            }
        }
        NSDictionary *params = [self parseParam:execStr];
        if (params.count == 0) {
            if (![matchedItem.command isEqualToString:@"main.html"]) {
                NSString * itemid = [execStr substringWithRange:NSMakeRange(5, execStr.length - 10)];
                execStr = [NSString stringWithFormat:@"%@?item_uid=%@",execStr,itemid];
                params = [self parseParam:execStr];
            }
           
        }
        if ([params[@"isForceWap"] isEqualToString:@"true"])
        {
            break;
        }
        if ([matchedItem.className isEqualToString:@"MKCouponViewController"] || [matchedItem.className isEqualToString:@"MKStoreListViewController"]) {
            matchedItem.needLogin = YES;
        }
        //需要登录，跳转到登录界面
        if (matchedItem.needLogin && ![getUserCenter isLogined])
        {
            MKLoginViewController *login = [MKLoginViewController create];
            login.successBlock = ^
            {
                if ([matchedItem.className isEqualToString:@"MKCouponViewController"]) {
                    //领取优惠券
                    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
                    MBProgressHUD *hud = [MBProgressHUD showMessage:nil inView:window wait:YES];
                    [MKNetworking MKSeniorPostApi:@"marketing/activity_coupon/exchange_by_id" paramters:@{@"coupon_id":_couponId} completion:^(MKHttpResponse *response) {
                        [hud hide:YES];
                        if (response.responseCode == 10000) {
                            //领取成功 跳转到优惠券列表
                            [self guideToItem:matchedItem withParams:params];
                        }else{
                            //领取失败
                            [MBProgressHUD showMessage:response.errorMsg wait:NO];
                        }
                    }];
                }else{
                    [self guideToItem:matchedItem withParams:params];
                }
                
            };
            [self guideToViewController:login forceModel:YES];
        }
        //已经登录
        else
        {
            if ([matchedItem.className isEqualToString:@"MKCouponViewController"]) {
                //领取优惠券
                [MKNetworking MKSeniorPostApi:@"marketing/activity_coupon/exchange_by_id" paramters:@{@"coupon_id":_couponId} completion:^(MKHttpResponse *response) {
                    if (response.responseCode == 10000) {
                        //领取成功 跳转到优惠券列表
                        [self guideToItem:matchedItem withParams:params];
                    }else{
                        //上传出生证
                        if (response.responseCode == 30800) {
                            QQYFirstMilkViewController *firstVC = [[QQYFirstMilkViewController alloc] init];
                            firstVC.couponId = _couponId;
                            [self guideToViewController:firstVC forceModel:NO];
                        }else{
                            //领取失败
                            [MBProgressHUD showMessage:response.errorMsg wait:NO];
                        }
                        
                    }
                }];
            }else{
                [self guideToItem:matchedItem withParams:params];
            }
            
            // [self guideToItem:matchedItem withParams:params];
            
        }
        return YES;
    }
    while (0);
    if (!ignore)
    {
        [self guideToWebViewControllerWithUrl:urlString];
    }
    return NO;
}
- (void)saveSelfCode:(NSString *)text{
    if ([text rangeOfString:@"self_code="].location != NSNotFound) {
        NSArray *arraySelf = [text componentsSeparatedByString:@"self_code="];
        NSString *selfCode = arraySelf.lastObject;
        NSArray *arrayCode = [selfCode componentsSeparatedByString:@"&"];
        NSString *sCode = arrayCode.firstObject;
        SaveSelfCode *se = [SaveSelfCode setUpSaveSelfCode];
        se.preCode = sCode;
        NSArray *  arrayId = [text componentsSeparatedByString:@"item_uid="];
        NSArray * arrayItem = [arrayId.lastObject componentsSeparatedByString:@"&"];
        NSString * itemID = arrayItem.firstObject;
        se.itemCode = itemID;
    }
}


- (void)guideToItem:(MKUrlGuideItem *)item withParams:(NSDictionary *)params
{
    if ([item.command isEqualToString:@"thirdStoreIndex.htm"]) {
        //如果跳转到第三方店铺
        if ([[params allKeys] containsObject:@"shop_id"]) {
            _thirdShopId = params[@"shop_id"];
        }else if ([[params allKeys] containsObject:@"storeId"]){
            _thirdShopId = params[@"storeId"];
        }
        
    }
    //分享模块没有使用控制器，单独处理
    if ([item.command isEqualToString:share_command])
    {
        [self dealWithShareCommandWithParam:params];
        return;
    }
    if (item.isMainTab)
    {
        if (self.isNavigating)
        {
            [self.delayGuideActions addObject:^
            {
                [getMainTabBar selectTab:NSClassFromString(item.className)];
            }];
        }
        else
        {
            [getMainTabBar selectTab:NSClassFromString(item.className)];
        }
        
        return;
    }
    
    Class vcClass = NSClassFromString(item.className);
    UIViewController *vc;
    if ([item.createMethod isEqualToString:@"create"])
    {
        vc = [vcClass performSelector:@selector(create)];
    }
    else
    {
        vc = [[vcClass alloc] init];
    }
    vc.hidesBottomBarWhenPushed = YES;
    
    for (MKUrlGuideParamItem *paramItem in item.params)
    {
        id v = params[paramItem.urlParamName];
        if (v == nil)
        {
            v = paramItem.defaultValue;
        }
        if (v != nil)
        {
            [vc setValue:v forKey:paramItem.classParamName];
        }
    }
    [self guideToViewController:vc forceModel:item.isModal];
}

- (void)guideToViewController:(UIViewController *)viewController forceModel:(BOOL)isModal
{
    if (self.isNavigating)
    {
        __weak __typeof(&*self)weakSelf = self;
        [self.delayGuideActions addObject:^
        {
            [weakSelf guideToViewController:viewController forceModel:isModal];
        }];
        return;
    }
    //如果有alertview的时候keywindow就取不对了
    UIViewController *topViewController = [self getTopViewController];
    
    if (!isModal && topViewController.navigationController != nil)
    {
        if ([viewController isKindOfClass:[MKMultipleShopsHomePageController class]]) {
            MKWebViewController *webViewController = [[MKWebViewController alloc] init];
            NSString * urlString = [NSString stringWithFormat:@"http://www.ybaby.com/mobile/thirdStoreIndex.htm?storeId=%@",_thirdShopId];
            NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [webViewController loadUrls:encodingString];
            [topViewController.navigationController pushViewController:webViewController animated:YES];
            return;
            
        }
        [topViewController.navigationController pushViewController:viewController animated:YES];
        return;
    }
    
    UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:viewController];
    [topViewController presentViewController:nv animated:YES completion:nil];
}

- (UIViewController *)getTopViewController
{
    //如果有alertview的时候keywindow就取不对了
    UIViewController *topViewController =  [[UIApplication sharedApplication].windows[0] topViewController];
    if ([topViewController isKindOfClass:[UITabBarController class]])
    {
        UITabBarController *t = (UITabBarController *)topViewController;
        topViewController = [t selectedViewController];
    }
    if ([topViewController isKindOfClass:[UINavigationController class]])
    {
        topViewController = [[(UINavigationController *)topViewController viewControllers] lastObject];
    }
    return topViewController;
}

- (void)guideToWebViewControllerWithUrl:(NSString *)urlString
{
    MKWebViewController *webViewController = [[MKWebViewController alloc] init];
    NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [webViewController loadUrls:encodingString];
    [self guideToViewController:webViewController forceModel:NO];
}

//将地址中的键值对拆成字典
- (NSDictionary *)parseParam:(NSString *)urlString;
{
    NSRange r = [urlString rangeOfString:@"?"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (r.location != NSNotFound)
    {
        NSString *paramStr = [urlString substringFromIndex:r.location + 1];
        NSArray *pps = [paramStr componentsSeparatedByString:@"&"];
        for (NSString *str in pps)
        {
            NSArray *p = [str componentsSeparatedByString:@"="];
            switch (p.count)
            {
                case 0:
                    continue;
                    break;
                case 1:
                    [params setObject:[NSNull null] forKey:[p[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                    break;
                default:
                {
                    NSString *p1 = [p[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSString *p0 = [p[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    [params setObject:p1 forKey:p0];
                    break;
                }
            }
        }
    }
    return params;
}

- (void)dealWithShareCommandWithParam:(NSDictionary *)params
{
//    ShareInfo *shareInfo = [[ShareInfo alloc] init];
//    
//    shareInfo.url = params[@"url"];
//    shareInfo.content = params[@"text"];
//    shareInfo.title = params[@"title"];
//    shareInfo.image = params[@"image"];
//    
//    NSString *app = params[@"app"];
//    ShareType type = ShareTypeAny;
//    
//    if ([app isEqualToString:@"weixin"])
//    {
//        type = ShareTypeWeixiSession;
//    }
//    else if ([app isEqualToString:@"pengyouquan"])
//    {
//        type = ShareTypeWeixiTimeline;
//    }
//    else if ([app isEqualToString:@"weibo"])
//    {
//        type = ShareTypeSinaWeibo;
//    }
//    [VEShareHelper readyToShareInfo:shareInfo toPlatform:type
//           withNavigationController:[self getTopViewController].navigationController
//                         completion:nil];
}

@end
